const Charts = require('../wx-chat/wxcharts.js'); // 引入wx-charts.js文件
const {
  http
} = require("../../../utils/apiutils")
import {
  formatTime, getMonday
} from '../../../utils/util'
Page({

  data: {
    pageNo: 1,
    total: 0,
    dataList: [],
    tabActive: 1,
    hasMore: true,
    loading: false,
    month: 1,
    option2: [{
      text: '一月',
      value: '1'
    },
    {
      text: '二月',
      value: '2'
    },
    {
      text: '三月',
      value: '3'
    },
    {
      text: '四月',
      value: '4'
    },
    {
      text: '五月',
      value: '5'
    },
    {
      text: '六月',
      value: '6'
    },
    {
      text: '七月',
      value: '7'
    },
    {
      text: '八月',
      value: '8'
    },
    {
      text: '九月',
      value: '9'
    },
    {
      text: '十月',
      value: '10'
    },
    {
      text: '十一月',
      value: '11'
    },
    {
      text: '十二月',
      value: '12'
    },
    ],
    factoryId: "",
    ym: new Date().getFullYear(),
    nzx: false,
    nbz: false,
    startX: 0,
    moveLeft: false,
    startTime: getMonday(new Date())
  },
  onLoad: function () {
    var m = new Date().getMonth()
    this.setData({
      month: this.data.option2[m].value,
    })
    // let istrue = getApp().globalData.check();
    // if(!istrue) return
    if (!getApp().globalData.userInfo.exist) {
      wx.showModal({
        title: "提示",
        content: "您尚未添加公司信息暂无法使用",
        cancelText: '稍后认证',
        confirmText: '去认证',
        success: function (e) {
          if (e.confirm) {
            wx.navigateTo({
              // url: '/pages/me/pages/companyInfo/companyInfo',
              url: '/pages/me/pages/savecompany/index',
            })
          }
          if (e.cancel) {
            http.laterCertification({}, res => {
              if (res.status == 200) {
                http.userInfo({}, res => {
                  if (res.code == 0) {
                    getApp().globalData.userInfo = res.data;
                  } else {
                    wx.showToast({
                      title: res.message,
                      icon: "none",
                    })
                  }
                }, err => { })
                wx.reLaunch({
                  url: '/pages/tabBar/home/index',
                })
              }

            }, err => { })
          }
        },
      })
      return
    }
    this.echartsPositionOf();
    this.getData()
  },
  ringGraphShow: function (data) {
    let series = [];
    let sum = 0;
    data.map(item => {
      sum += item.payAmount;
      series.push({
        name: item.position,
        data: item.payAmount,
        formatter: item.name + '/' + item.payAmount,
        stroke: false
      })
    })
    let pie = {
      canvasId: 'ringGraph', // canvas-id
      type: 'ring', // 图表类型，可选值为pie, line, column, area, ring
      series,
      disablePieStroke: true,
      width: 350, // 宽度，单位为px
      height: 250, // 高度，单位为px
      legend: true, // 是否显示图表下方各类别的标识
      dataLabel: true, // 是否在图表中显示数据内容值
      title: {
        name: (sum / 100) + '元',
        color: '#7cb5ec',
        fontSize: 14,
      },
      subtitle: {
        name: '当前总支出',
        color: '#666666',
        fontSize: 14
      },
      extra: {
        ringWidth: 25, //圆环的宽度
        pie: {
          offsetAngle: -45 //圆环的角度
        }
      }
    };
    new Charts(pie);
  },
  getData() {
    http.echartsCostPerDay(this.data.startTime, res => {
      if (res.code == 0) {
        let data = res.data;
        this.circleGraphShow(data);
      } else {
        wx.showToast({
          title: res.message,
          icon: "none"
        })
      }
    }, err => {
      wx.showToast({
        title: err,
        icon: "none"
      })
    })

  },
  circleGraphShow: function (data) {
    let categories = [];
    let series = [];
    data.forEach((item) => {
      let date = item.xDay.split('-');
      categories.push(date[1] + '-' + date[2])
      series.push(item.payAmount * 1)
    })
    let circle = {
      canvasId: 'circleGraph', // canvas-id
      dataPointShape: "circle",
      type: 'line',
      extra: {
        lineStyle: 'curve' //线条的形状（弧形）
      },
      categories: categories,
      series: [{
        name: ' ',
        data: series,
        format: function (val) {
          return (val / 100).toFixed(2) + '元';
        }
      }],
      yAxis: {
        // title: '支付金额 (元)',
        format: function (val) {
          return (val / 100).toFixed(2);
        },
        fontColor: "red",
        titleFontColor: "red",
      },
      ym: new Date().getFullYear(),
      width: 350,
      height: 250,
      dataLabel: true

    }
    new Charts(circle);
  },
  getComInfo: function () {
    var data = {}
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getComInfo(data,
      function (res) {
        wx.hideLoading()
        console.log("-----已完成任务列表---", res);
        if (res.success) {
          if (res.data && res.data.id) {
            that.setData({
              factoryId: res.data.id
            })
            // that.getMonthData();
            // that.echartsPositionOf()
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })

  },
  echartsPositionOf: function () {
    // 获取饼图 数据
    http.echartsPositionOf(this.data.startTime, res => {
      if (res.data.length > 0) {
        this.setData({
          nbz: false
        })
        this.ringGraphShow(res.data)
      } else {
        this.setData({
          nbz: true
        })
      }
    }, err => {
      wx.showToast({
        title: err,
        icon: 'none'
      })
    })
    return
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getechartsPositionOf(data,
      function (res) {
        wx.hideLoading()
        console.log("-----职位占比---", res);
        if (res.code == "0") {
          if (res.data.length == 0) {
            that.setData({
              nbz: true,
            })
          } else {
            that.setData({
              nbz: false,
            })
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })
  },
  getMonthData: function () {
    var data = {
      factoryId: this.data.factoryId,
      ym: this.data.ym + "-" + this.data.value2,
    }
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getMonthData(data,
      function (res) {
        wx.hideLoading()
        console.log("-----月报表---", res);
        if (res.code == "0") {
          if (res.data && res.data.id) {

          }
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })


  },
  onShow() {
    if (getApp().globalData.exist != "0") {
      this.getComInfo()
    }
    // this.ringGraphShow();
    // this.circleGraphShow()
  },
  onReady() { },
  touchStart(e) {
    if (e.touches.length == 1) {
      this.setData({
        startX: e.touches[0].clientX
      });
    }
  },
  touchEnd(e) {
    if (e.changedTouches.length == 1) {
      let diff = e.changedTouches[0].clientX - this.data.startX;
      let date = new Date(this.data.startTime).getTime();
      let left = date - (7 * 24 * 60 * 60 * 1000);
      let right = date + (7 * 24 * 60 * 60 * 1000);
      if (diff > 50) {
        this.data.startTime = formatTime(left);
      } else if (diff < 0 && diff < -50) {
        this.data.startTime = formatTime(right);
      }
      wx.nextTick(() => {
        this.getData();
      })
    }
  },
  onchange(e) {
    let index = e.detail.value;
    this.setData({
      month: this.data.option2[e.detail.value].value,
      startTime: new Date().getFullYear() + '-' + (index < 9 ? '0' + (index * 1 + 1) : index * 1 + 1) + "-01"
    })
    this.getData()
  },
  getList() {
    // 获取 开支列表 
    var data = {
      "pageNo": this.data.pageNo, //手机号码
      "pageSize": "10", //密码
    }
    if (this.data.loading) {
      return false;
    }
    if (this.data.loading) return false;
    if (!this.data.hasMore) {
      wx.showToast({
        title: '没有更多数据',
        icon: "none"
      })
      return false;
    }
    this.data.loading = true;
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.billslist({},
      (res) => {
        wx.hideLoading()
        debugger
        if (res.code == 0) {
          var arr = [];
          let hasMore = false;
          if (res.data.length > 0) {
            hasMore = true;
            arr = res.data;
          }
          that.setData({
            dataList: [...that.data.dataList, ...arr],
            pageNo: that.data.pageNo + 1,
            hasMore,
            loading: false
          })
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
        that.data.loading = false;
      },
      function (err) {
        wx.hideLoading()
      })

  },
  tabChange(e) {
    this.setData({
      tabActive: e.detail.name
    })
    if (e.detail.name == 2) {


      this.data.pageNo = 1;
      this.data.dataList = [];
      this.data.hasMore = true;
      this.getList()
    } else {
      let istrue = getApp().globalData.check();
      if (!istrue) return
      this.getData();
      this.echartsPositionOf()
    }
  },
  listClick(e) {
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pages/home/pages/billdtl/billdtl?id=' + item.jobId
    })
  },
  backmoney(e) {
    let id = e.currentTarget.dataset.id;
    wx.showLoading()
    http.backmoney(id, (res) => {
      this.data.hasMore = true;
      this.data.pageNo = 1;
      this.data.loading = false;
      this.data.dataList = [];
      wx.hideLoading();
      wx.showToast({
        title: '操作成功',
        icon: "none",
        success() {
          this.getList();
        }
      })
    }, err => {
      wx.hideLoading()
    })
  }
});